<script>
import { defineComponent, reactive, ref, toRaw } from 'vue'
import MakeForm, { MakeFormState } from '@Components/makeForm'
import DataTable from '@Components/dataTable'
import {
  adminSubList,
  adminSubRegister,
  adminSubModify,
  adminSubEnable,
  adminSubReset,
  authRoleList,
} from '@Config/server/api'
import { message } from 'ant-design-vue'
import { createPagination, Messages, confirm } from '@Config/config'
import { useRoute, useRouter } from 'vue-router'
import { useUrl, transform_pre_fn } from '@Hooks/url'
import { useWin } from '@Hooks/win'
import SubUserForm from '@Page/role/components/subUserForm'
import { maxSearchValue } from '@Untils'
import { sexTypeList, getOneSex } from '@Page/role/config'
import { cloneDeep, findIndex } from 'lodash'
export default defineComponent({
  components: {
    DataTable,
    MakeForm,
  },
  setup(props, context) {
    let roleList = reactive({ data: [] })
    authRoleList({ index: 1, size: 10000 }).then((x) => {
      roleList.data = x.data.records
    })

    let tableData = reactive({
      data: {
        source: [],
        columns: [
          {
            key: 'nickname',
            dataIndex: 'nickname',
            title: '姓名',
            width: '20%',
          },

          {
            key: 'phone',
            dataIndex: 'phone',
            title: '手机号',
            width: '15%',
          },

          {
            key: 'description',
            dataIndex: 'description',
            title: '描述',
            width: '30%',
          },
          {
            key: 'operatorName',
            dataIndex: 'operatorName',
            title: '主账号',
            width: '10%',
          },
          {
            key: 'dataStatus',
            dataIndex: 'dataStatus',
            title: '状态',
            width: '10%',
          },
          {
            key: 'operation',
            dataIndex: 'operation',
            title: '操作',
            width: '15%',
          },
        ],
      },
    })

    let custom = [
      {
        key: 'nickname',
        bodyFn: (text, record, index) => {
          let _sex = getOneSex((x) => x.value == record.sex)
          return (
            <a-space direction="vertical">
              <a-space>
                <span class="ant-statistic-title">姓名</span>
                <span>{record.nickname}</span>
              </a-space>
              <a-space>
                <span class="ant-statistic-title">登录名</span>
                <span>{record.userName}</span>
              </a-space>

              <a-space>
                <span class="ant-statistic-title">性别</span>
                <span>{_sex.label}</span>
              </a-space>
            </a-space>
          )
        },
      },
      {
        key: 'operation',
        bodyFn: (text, record, index) => {
          return (
            <a-space direction="vertical">
              <a-button
                type="primary"
                onClick={() => {
                  win({
                    params: {
                      record: { ...toRaw(record) },
                      type: 2,
                      roleList: roleList.data,
                    },
                    attr2: {
                      title: '编辑账号',
                    },
                  })
                }}
                loading={record.local_loading}
              >
                编辑
              </a-button>
              <a-popconfirm
                title="确定要重置密码吗?"
                onText="确定"
                onConfirm={async () => {
                  record.local_loading = true
                  let _result = await adminSubReset({ id: record.id })
                  record.local_loading = false

                  if (_result.code == 0) {
                    Messages.add(message.success('密码重置成功'))
                  } else {
                    Messages.add(message.error(`密码重置失败[${_result.msg}]`))
                  }
                }}
              >
                <a-button type="primary" danger loading={record.local_loading}>
                  密码重置
                </a-button>
              </a-popconfirm>
            </a-space>
          )
        },
      },
      {
        key: 'sex',
        bodyFn: (text, record, index) => {
          let _r = getOneSex((x) => x.value == record.sex)
          return <span>{_r.label}</span>
        },
      },
      {
        key: 'dataStatus',
        bodyFn: (text, record, index) => {
          return (
            <a-switch
              loading={record.local_loading}
              checked={record.dataStatus == 1 ? true : false}
              onChange={async (e) => {
                record.local_loading = true
                let _result = await adminSubEnable({
                  id: record.id,
                  dataStatus: e ? 1 : 0,
                })
                if (_result.code != 0) {
                  record.local_loading = false
                  Messages.add(message.error(`操作错误 [${_result.msg}]`))
                } else {
                  Messages.add(message.success('操作成功'))

                  let newItem = cloneDeep({
                    ...toRaw(record),
                    dataStatus: e ? 1 : 0,
                    local_loading: false,
                  })
                  tableData.data.source.splice(index, 1, newItem)
                }
              }}
            ></a-switch>
          )
        },
      },
    ]
    let route = useRoute()
    let router = useRouter()

    let searchData = async () => {
      fromStateToQuery({
        path: route.path,
      })
    }
    //分布配置
    let pagination = reactive({
      data: createPagination(searchData, true, false),
    })
    //切换分页
    // pagination.data.onChange = (pageNumber, pageSize) => {
    //   pagination.data.current = pageNumber
    //   pagination.data.pageSize = pageSize
    //   searchData()
    // }
    let form_config = [
      {
        key: 'userName',
        initValue: null,
        uiType: 'input',
        col: { span: 8 },
        formItem: { label: '登录账号' },
        attr: {
          placeholder: '请输入登录账号',
          allowClear: true,
          ...maxSearchValue(),
        },
      },
      {
        key: 'nickname',
        initValue: null,
        uiType: 'input',
        col: { span: 8 },
        formItem: { label: '姓名' },
        attr: {
          placeholder: '请输入姓名',
          allowClear: true,
          ...maxSearchValue(),
        },
      },

      {
        key: 'sex',
        initValue: null,
        uiType: 'dselect',
        col: { span: 8 },
        source: sexTypeList(),
        formItem: { label: '性别' },
        attr: {
          placeholder: '请选择性别',
          allowClear: true,
          ...maxSearchValue(),
        },
      },
    ]

    let form_state = reactive({ data: MakeFormState(form_config) })
    let _bak_statue = { ...toRaw(form_state.data) }

    let loading = reactive({ search_loading: false })

    let { fromStateToQuery } = useUrl({
      fn: async () => {
        loading.search_loading = true
        let _params = {
          size: pagination.data.pageSize,
          index: pagination.data.current,
          ...form_state.data,
        }
        let _result = await adminSubList(_params)
        loading.search_loading = false
        if (_result.code != 0) {
          Messages.add(message.error(`获取数据发生错误[${_result.msg}]`))
          return
        }
        tableData.data.source = _result.data?.records
        pagination.data.total = _result.data?.total
        pagination.data.current = _result.data?.index
        pagination.data.pageSize = _result.data?.size
      },
      formState: [
        {
          key: 'userName',
          fn: transform_pre_fn['fn.string'],
        },
        {
          key: 'nickname',
          fn: transform_pre_fn['fn.string'],
        },
        {
          key: 'sex',
          fn: transform_pre_fn['fn.number'],
        },
      ],
    })

    let [win] = useWin({
      component: (
        <SubUserForm
          onResult={async ({ params, exteal, innerCallBack }) => {
            if (exteal.type == 1) {
              //创建用户
              let _result = await adminSubRegister(params)

              if (_result.code != 0) {
                Messages.add(message.error(`操作失败[${_result.msg}]`))
              } else {
                //创建成功
                tableData.data.source.unshift(_result.data)
              }
              innerCallBack(_result)
            } else {
              //编辑用户
              let _index = findIndex(tableData.data.source, {
                id: exteal.record.id,
              })
              tableData.data.source[_index].local_loading = true
              let _result = await adminSubModify({
                ...params,
                id: exteal.record.id,
              })
              tableData.data.source[_index].local_loading = false

              if (_result.code != 0) {
                Messages.add(message.error(`操作失败2[${_result.msg}]`))
              } else {
                //编辑成功
                Messages.add(message.success(`操作成功`))
                let newItem = cloneDeep({
                  ...toRaw(exteal.record),
                  ...params,
                  local_loading: false,
                })

                tableData.data.source.splice(_index, 1, newItem)
              }
              innerCallBack(_result)
            }
          }}
        />
      ),
      attr: {
        title: '账号',
      },
    })
    let createSubUser = () => {
      win({
        params: {
          roleList: roleList.data,
        },
        attr2: {
          title: '创建账号',
        },
      })
    }

    let resetHandler = () => {
      form_ref.value.resetState(cloneDeep(_bak_statue))
      pagination.data.current = 1
      searchData()
    }

    let searchHandler = () => {
      pagination.data.current = 1
      searchData()
    }

    let form_ref = ref()

    return {
      resetHandler,
      tableData,
      pagination,
      loading,
      custom,
      createSubUser,
      form_config,
      form_state,
      searchData,
      form_ref,
      searchHandler,
    }
  },
  render() {
    return (
      <>
        <a-row gutter={[20, 20]}>
          <a-col span={24}>
            <MakeForm
              ref="form_ref"
              formConfig={this.form_config}
              value={this.form_state.data}
              enterCallBack={() => {
                this.pagination.data.current = 1
                this.searchData()
              }}
              class="search_form"
            />
          </a-col>

          <a-col span={24}>
            <a-space>
              <a-button
                type="primary"
                onClick={this.searchHandler}
                loading={this.loading.search_loading}
              >
                搜索
              </a-button>
              <a-button
                type="primary"
                danger
                onClick={this.resetHandler}
                loading={this.loading.search_loading}
              >
                重置
              </a-button>
            </a-space>
          </a-col>
          <a-col span={24}>
            <DataTable
              data={this.tableData}
              uiAttr={{
                scroll: { x: null },
                tableLayout: 'fixed',
                bordered: true,
              }}
              custom={this.custom}
              loading={this.loading}
            >
              <a-space>
                <a-button type="primary" onClick={this.createSubUser}>
                  创建子账号
                </a-button>
              </a-space>
            </DataTable>
          </a-col>
        </a-row>

        <a-affix {...this.pagination_affix_attr()}>
          <div class="affix">
            <a-pagination {...this.pagination.data} />
          </div>
        </a-affix>
      </>
    )
  },
})
</script>
